package com.hs.utils;

import com.hs.entity.pojo.LoginUser;
import com.hs.entity.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

@Slf4j
public class SecurityUserHolder {

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {
        Object principal = getAuthentication().getPrincipal();
        if (principal instanceof String) {
            log.info((String) principal);
        }
        if (principal instanceof LoginUser) {
            return (LoginUser) principal;
        }
        return new LoginUser();
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public static Boolean isAdmin() {
        Integer id = getLoginUser().getUser().getId();
        return id != null && 1L == id;
    }

    public static Integer getUserId() {
        return OptUtil.of(getLoginUser()).get(LoginUser::getUser).get(User::getId).get();
    }
}